﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace HVACWebService.Common
{
    public static class StringEx
    {
        public static bool IsInt(this string str)
        {
            return !string.IsNullOrEmpty(str) && Regex.IsMatch(str, @"^[+-]?\d*$");
        }

        public static bool IsDouble(this string str)
        {
            return !string.IsNullOrEmpty(str) && Regex.IsMatch(str, @"^-?\d+(\.\d+)?$");
        }

        public static T ToObject<T>(this string value)
        {
            if (string.IsNullOrWhiteSpace(value)) return default(T);
            try
            {
                return (T) Convert.ChangeType(value, typeof (T));
            }
            catch (Exception)
            {
                // ignored
            }
            return default(T);
        }

        public static int GetByteLength(this string str)
        {
            if (str.Length == 0) return 0;
            var ascii = new ASCIIEncoding();
            var tempLen = 0;
            var s = ascii.GetBytes(str);
            foreach (var t in s)
            {
                if (t == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
            }
            return tempLen;
        }
    }
}